import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "../store/user";
import router from "../router";

const instance = axios.create({
  baseURL: "",
  timeout: 300000,
});

instance.interceptors.request.use(
  function (config) {
    const userStore = useUserStore();
    const token = userStore.getToken;
    if (token) {
      config.headers["Authorization"] = 'Bearer ' +  token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 0 || res.data.code === 200) {
      return res.data;
    } 
    if(res.data.code === 500 || res.data.code === 412 || res.data.code === 510) {
      ElMessage.error(res.data.message);
      return Promise.reject(res.data.message);
    }
    return res.data
  },
  (error) => {
    if(error.response?.data?.code === 401) {
      const userStore = useUserStore();
      userStore.clearToken();
      userStore.clearUserInfo();
      userStore.clearAccessRoutes();
      ElMessage.error(error.response?.data?.message);
      router.push('/login');
      return Promise.reject(error);
    }
    ElMessage.error(error.message);
    return Promise.reject(error);
  }
);

// 导出配置好的实例
export default instance;
